<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20; // 默认显示20条记录

try {
    // 获取用户提现记录
    // 使用直接插入的方式设置LIMIT值，而不是使用参数占位符
    $stmt = $pdo->prepare("
        SELECT 
            id, 
            amount, 
            fee,
            actual_amount,
            withdraw_method, 
            account AS account_info,
            status, 
            created_at, 
            processed_at
        FROM withdraw_records 
        WHERE user_id = ? 
        ORDER BY created_at DESC
        LIMIT {$limit}
    ");
    $stmt->execute([$user_id]);
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 格式化日期和状态
    foreach ($records as &$record) {
        $record['created_at'] = date('Y-m-d H:i', strtotime($record['created_at']));
        $record['processed_at'] = $record['processed_at'] ? date('Y-m-d H:i', strtotime($record['processed_at'])) : null;
        
        // 格式化金额
        $record['amount'] = floatval($record['amount']);
        $record['fee'] = floatval($record['fee']);
        $record['actual_amount'] = floatval($record['actual_amount']);
        
        // 翻译状态
        switch ($record['status']) {
            case 'pending':
                $record['status_text'] = '处理中';
                break;
            case 'processing':
                $record['status_text'] = '处理中';
                break;
            case 'completed':
                $record['status_text'] = '已完成';
                break;
            case 'rejected':
                $record['status_text'] = '已拒绝';
                break;
            case 'failed':
                $record['status_text'] = '失败';
                break;
            default:
                $record['status_text'] = $record['status'];
        }
    }
    
    echo json_encode([
        'success' => true,
        'records' => $records
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => '获取提现记录失败: ' . $e->getMessage()
    ]);
}
?>
